//index.js
//获取应用实例
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    initialState: false, // 页面元素初始显示状态
    pullDown:false, //下拉刷新页面
    user:{},
    tabbar:{},
    array: [
      { url: '/pages/review_knowledge/review_knowledge', class: 'icon-shijian', text: '温故知新' },
      { url: '/pages/study_task/study_task', class: 'icon-renwu1', text: '学习任务'},
      { url: '/pages/atlas_database/atlas_database', class: 'icon-zhishitupu', text: '精品图谱' },
      { url: '/pages/webView/webView', class: 'icon-baogao', text: '学情报告' }
    ],
    tupu: [],
    commend: [],
    cStudy: false,
    aCommend:false
  },
  /**
   * 扫描条形码或二维码
   */
  sweepCode: function(){
    var _this = this,
    user_id = wx.getStorageSync('userId');
    // wx.navigateTo({
    //             url: '/pages/testImg/testImg?app_id=' + 1101 + '&paper_download_task_id=' + 2249 + '&page=' + 1 + '&download_task_id=' + 332
    //           })
    wx.scanCode({
      onlyFromCamera: true,//仅仅相机
      success: (res) => {
        console.log(res);
        var _result = res.result;
        if (res.path){
          var path = res.path.replace('code=', ''),
            pathIndex = path.indexOf('?'),
            parseUrl = path.substr(pathIndex + 1, path.length);
          var scene = decodeURIComponent(parseUrl).replace(/'/g, "");
          _result = scene.split("+");
          wx.request({
            url: app.globalData.URL + '/kmapping/WebAppAjax/checkPageStatus?' + app.globalData.URLBOOL,
            method: 'GET',
            data: {
              download_task_id: _result[3],
              paper_download_task_id: _result[1],
              user_id: user_id,
              wechat_flag: 1
            },
            success: function (_res) {
              var res = _res.data;
              if (res.error_code == 0) {
                wx.navigateTo({
                  url: '/' + path
                })
              } else {
                wx.showToast({
                  title: res.error_msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          })
        }else {
          _result = _result.split("&");
          if (_result[0] != 1101 && _result[3] != 1101) {
            wx.showToast({
              title: '该套试题未启用!',
              icon: 'none',
              mask: true,
              duration: 2000
            })
            _this.sweepCode();
          } else {
            wx.request({
              url: app.globalData.URL + '/kmapping/WebAppAjax/checkPageStatus?' + app.globalData.URLBOOL,
              method: 'GET',
              data: {
                download_task_id: _result[3],
                paper_download_task_id: _result[1],
                user_id: user_id,
                wechat_flag: 1
              },
              success: function (_res) {
                var res = _res.data;
                if (res.error_code == 0) {
                  wx.navigateTo({
                    url: '/pages/testImg/testImg?online=0&app_id=' + _result[0] + '&paper_download_task_id=' + _result[1] + '&page=' + _result[2] + '&download_task_id=' + _result[3]
                  })
                } else {
                  wx.showToast({
                    title: res.error_msg,
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            })
          }
        }
       
      },
      //错误返回
      fail: (res) => {
      }
    })
  },
  /**
   * 获取用户信息
   */
  getUserInfoByUid: function(){
    wx.showLoading({
      title: 'loading...',
    });
    var that = this;
    var _array = that.data.array;
    wx.request({
      url: app.globalData.URL + '/kmapping/WebAppAjax/getUserInfoByUid?' + app.globalData.URLBOOL,
      dataType: 'json',
      method: 'GET',
      success: function (res) {
        wx.hideLoading();
        var _res = res.data;
        if (_res.error_code == 0) {
          var _user = _res.user;
          that.setData({
            'user': _user
          })
          var hxUser = res.data.user.node_id + '_' + res.data.user.uid;
          wx.setStorageSync('userId', res.data.user.uid);
          wx.setStorageSync('myUsername', hxUser);
          var hxUserIds = app.globalData.huanxin_msg_user_ids
          for (let i = 0; i < hxUserIds.length; i++){
            if (hxUserIds[i] == res.data.user.uid){
              app.globalData.hxConfigStatus = true
            }
          }
          app.hxlogin();
          var learn_report_url = that.data.user.learn_report_url;
          _array[3].url = '/pages/webView/webView?url=' + learn_report_url.replace('?', '&');
          that.setData({
            array: _array
          })
        }
      }
    })
  },

  /**
   * 获取继续学习列表
   */
  getUserKmappingTask:function(){
    var that = this,
      pullDown = that.data.pullDown;
    if (!pullDown){
      wx.showLoading({
        title: 'loading...',
      });
    } 
    wx.request({
      url: app.globalData.URL + '/kmapping/WebAppAjax/getUserKmappingTask?' + app.globalData.URLBOOL,
      dataType: 'json',
      method: 'GET',
      data: {
        type: 0,
        page: 1,
        num: 2,
        learn_status: 0
      },
      success: function (res) {
        var _res = res.data;
        if (_res.error_code == 0) {
          var _tupu = _res.data; console.log('----------:', _tupu)
          that.setData({
            'tupu': _tupu,
            'cStudy': true
          })
        }
        else {
          that.setData({
            'cStudy': false
          })
        }
        that.setData({
          initialState: true
        })
        that.getAiList();
      }
    })
  },

  /**
   * 获取AI推荐列表
   */
  getAiList: function(){
    var that = this,
      pullDown = that.data.pullDown;
    wx.request({
      url: app.globalData.URL + '/kmapping/WebAppAjax/getAiList?' + app.globalData.URLBOOL,
      dataType: 'json',
      method: 'GET',
      data: {
        page: 1,
        num: 3,
        wechat_flag: 1
      },
      success: function (res) {
        wx.hideLoading();
        var _res = res.data;
        if (_res.error_code == 0) {
          var _commend = _res.data;
          that.setData({
            'commend': _commend,
            'aCommend': true
          })
        }
        else {
          that.setData({
            'aCommend': false
          })
        }
        if (pullDown){
          that.setData({
            pullDown: false
          })
          wx.hideNavigationBarLoading();
          wx.stopPullDownRefresh();
        }
      }
    })
  },
 
  getCollected: function (index, arrName) {
    var that = this,
      arr = that.data[arrName];
    wx.request({
      url: app.globalData.URL + '/index.php?app=interface&mod=Collection&act=addCollection&' + app.globalData.URLBOOL,
      dataType: 'json',
      method: 'GET',
      data: {
        type: 213,
        id: arr[index].kmapping_id
      },
      success: function (res) {
        var _res = res.data;
        if (_res.error_code == 0) {
          arr[index].is_collection = 1;
          if (arrName == 'tupu'){
            that.setData({
              tupu: arr,
            })
          }else {
            that.setData({
              commend: arr,
            })
          }
          that.updataCollectStatus(arr[index].kmapping_id, 1);
          wx.showToast({
            title: '收藏成功',
            icon: 'none',
            duration: 2000
          })
        }else {
          wx.showToast({
            title: '收藏失败',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },

  getunCollected: function (index, arrName) {
    var that = this,
      arr = that.data[arrName];
    wx.request({
      url: app.globalData.URL + '/index.php?app=interface&mod=Collection&act=deleteCollection&' + app.globalData.URLBOOL,
      dataType: 'json',
      method: 'GET',
      data: {
        type: 213,
        id: arr[index].kmapping_id
      },
      success: function (res) {
        var _res = res.data;
        if (_res.error_code == 0) {
          arr[index].is_collection = 0;
          if (arrName == 'tupu') {
            that.setData({
              tupu: arr,
            })
          } else {
            that.setData({
              commend: arr,
            })
          }
          that.updataCollectStatus(arr[index].kmapping_id, 0);
          wx.showToast({
            title: '取消收藏成功',
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '取消收藏失败',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },

  collectHandle: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,
      arrName = e.currentTarget.dataset.name;
    that.getCollected(index, arrName);
  },

  uncollectHandle: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,
      arrName = e.currentTarget.dataset.name;
    that.getunCollected(index, arrName);
  },

  /**
   * 收藏或取消收藏操作更新之后更新首页相关图谱的收藏状态
  */
  updataCollectStatus: function (kmapping_id, status) {
    var _this = this;
    var tupu = _this.data.tupu,
      commend = _this.data.commend;
    for (let i = 0; i < tupu.length; i++) {
      if (tupu[i].kmapping_id == kmapping_id) {
        tupu[i].is_collection = status;
      }
    }
    for (let i = 0; i < commend.length; i++) {
      if (commend[i].kmapping_id == kmapping_id) {
        commend[i].is_collection = status;
      }
    }
    _this.setData({
      tupu: tupu,
      commend: commend
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.changeTabBar(); 
    wx.showLoading({
      title: 'loading...'
    })
    var that = this;
    app.configInfo(that);
  },

  index: function(){
    var _this = this;
    app.setUrlBool();
    _this.getUserInfoByUid();
    _this.getUserKmappingTask();
  },

  /**                                                                                             
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    var that = this;
    that.setData({
      pullDown: true
    })
    that.getUserKmappingTask();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})

